package zhr.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import zhr.store.common.BaseContext;
import zhr.store.common.Result;
import zhr.store.common.ValidateCodeUtils;
import zhr.store.domain.Employee;
import zhr.store.domain.User;
import zhr.store.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 分页查询用户信息
     *
     * @param page
     * @param pageSize
     * @param phone
     * @return
     */
    @GetMapping("/page")
    public Result<Page> showUser(int page, int pageSize, String phone) {
        //构建分页构造器
        Page pageShow = new Page(page, pageSize);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //构建查询条件
        if (phone != null) {
            wrapper.like(User::getPhone, phone);
        }
        //添加排序条件
        wrapper.orderByDesc(User::getUpdateTime);
        //执行查询
        userService.page(pageShow,wrapper);
        return Result.success(pageShow);
    }
    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @PostMapping
    public Result<String> insertUser(@RequestBody User user) {
        //1.设置初始密码并进行加密处理
        user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //2.进行添加用户操作
        userService.save(user);
        return Result.success("添加用户成功");
    }
    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<User> selectById(@PathVariable Long id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //构建查询条件
        wrapper.eq(User::getId, id);
        //执行查询
        User user = userService.getOne(wrapper);
        return Result.success(user);
    }
    /**
     * 根据id修改用户状态
     *
     * @param user
     * @return
     */
    @PutMapping
    public Result<String> updateEmployee(@RequestBody User user) {
        //执行修改
        userService.updateById(user);
        return Result.success("用户信息修改成功");
    }
    /**
     * 获取验证码
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user) {
        //获取手机号
        String phone = user.getPhone();
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info(code);
        //发送验证码
        //将验证码存入redis,并设置有效期60s
        redisTemplate.opsForValue().set(phone, code, 60, TimeUnit.SECONDS);
        return Result.success("短信发送成功");
    }
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody Map usermap){
        LambdaQueryWrapper<User> userLambdaQueryWrapper =new LambdaQueryWrapper<>();
        //获取手机号
        String phone = usermap.get("phone").toString();
        //获取用户名
        String username = usermap.get("username").toString();
        //判断手机号是否注册
        userLambdaQueryWrapper.eq(User::getPhone,phone);
        User one = userService.getOne(userLambdaQueryWrapper);
        if (one != null){
            return Result.error("手机号已注册");
        }
        //判断用户名是否注册
        userLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        User one1 = userService.getOne(userLambdaQueryWrapper);
        if (one1 != null){
            return Result.error("用户名已注册");
        }
        //判断验证码是否正确
        //获取用户输入验证码
        String userCode = usermap.get("code").toString();
        //获取Redis中验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (userCode != null && code.equals(userCode)) {
            //将密码md5处理
            String password = usermap.get("password").toString();
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            //注册
            User user = new User();
            user.setPhone(phone);
            user.setPassword(password);
            user.setUsername(username);
            userService.save(user);
            //redis中删除验证码
            redisTemplate.delete(phone);
            return Result.success("注册成功");
        }
        return Result.error("验证码错误");
    }
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody User user, HttpServletRequest request){
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断用户名或手机号是否存在
        String phone = user.getPhone().toString();
        String username =user.getPhone().toString();
        userLambdaQueryWrapper.eq(User::getPhone,phone).or().eq(User::getUsername,username);
        //查询
        User one = userService.getOne(userLambdaQueryWrapper);
        if (one == null){
            return Result.error("用户不存在");
        }
        String password = user.getPassword().toString();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!one.getPassword().equals(password)){
            return Result.error("密码错误");
        }
        //登录成功将用户id存入session
        HttpSession session = request.getSession();
        session.setAttribute("user",one.getId());
        return Result.success(user);
    }
    /**
     * 用户退出
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        //清除session
        request.getSession().removeAttribute("user");
        return Result.success("退出成功");
    }
}
